<?php

namespace App\Models;

use DB;

class Member extends BaseModel
{
    protected $table = "member";
    public $redisTable = 'member';

    /* 用户模型自动验证 */
    protected $_validate = [
        'xcx_openid' => 'required|unique:member,xcx_openid',
        'shop_id' => 'required',
        'admin_id' => 'required',
    ];

    protected $_message = [
        'xcx_openid.required' => '未获取到用户微信信息',
        'xcx_openid.unique' => '该用户已存在',
        'shop_id.required' => '未获取到店铺信息',
        'admin_id.required' => '未获取到商户信息',
    ];


    public function cash()
    {
        return $this->hasOne('App\Models\MemberCash', 'mid', 'id');
    }

    public function address()
    {
        return $this->hasOne('App\Models\Address', 'mid', 'id');
    }

    public function memberWaterBill()
    {
        return $this->hasMany('App\Models\MemberWaterBill', 'mid', 'id');
    }

    public function memberCommission()
    {
        return $this->hasOne('App\Models\MemberCommission', 'mid', 'id');
    }

    public function worker()
    {
        return $this->hasOne('App\Models\Worker', 'id', 'worker_id');
    }

    public function getInfoWithCashById()
    {
        return $this->_getJionOne('cash', ['id' => request('mid')]);
    }

//    public function getMemberList()
//    {
//        $keyword = request('keyword');
//        $type = request('type', 0);
//
//        $cashFields = 'id,lose_pay,self_bucket,cash_bucket,cash,water_dispenser,water_dispenser_cash,status,description,mid';
//        $billFields = 'goods_name,rest_num,mid';
//        $addressFields = 'address,mid';
//        $pageSize = 15;
//        $pageLength = 10;
//
//        $this->_openQueryLog();
//        $rows = $this->select("member.*")->orderBy("id","asc");
//        if(session('platIdentify') == 'admin'){
//            if(!is_administrator()) {
//                $rows = $rows->where("member.admin_id", plat_admin_id());
//            }
//        } else {
//            $rows = $rows->where("member.shop_id", session('account')['shop_id']);
//        }
//        if($keyword && $type) {
//            switch($type) {
//                case 1:
//                    $rows = $rows->where("member.id", $keyword);
//                    break;
//                case 2:
//                    $rows = $rows->where("member.name",'like',"%{$keyword}%");
//                    break;
//                case 3:
//                    $rows = $rows->where("member.mobile",'like',"%{$keyword}%");
//                    break;
//                case 4:
//                    $rows = $rows->where("member.company_name",'like',"%{$keyword}%");
//                    break;
//                case 5:
//                    $rows = $rows->leftjoin("address",'address.mid','=','member.id')
//                        ->where("address.address",'like',"%{$keyword}%")
//                        ->where("address.is_default",1);
//                    break;
//            }
//        }
//        $rows = $rows->paginate($pageSize);
//        $rows->appends([
//            'keyword' => $keyword,
//            'type' => $type
//        ]);
//
//        if(count($rows->items())) {
//            $ids = $rows->map(function($item) {
//                return $item->id;
//            })->toArray();
//            $addresses = Address::whereIn("mid", $ids)->where("is_default", 1)->select(DB::raw($addressFields))->get()->toArray();
//            $cashes = MemberCash::whereIn("mid", $ids)->select(DB::raw($cashFields))->get()->toArray();
//            $bills = MemberWaterBill::whereIn("mid", $ids)->select(DB::raw($billFields))->get()->toArray();
//
//            foreach($rows->items() as $item) {
//                $item->cash = [];
//                $item->member_water_bill = [];
//                $item->default_address = [];
//                foreach($cashes as $cash){
//                    if($cash['mid'] == $item->id){
//                        $item->cash = $cash;
//                    }
//                }
//
//                $temp = [];
//                foreach($bills as $key=>$bill){
//                    if($bill['mid'] == $item->id){
//                        array_push($temp, $bill);
//                    }
//                }
//                $item->member_water_bill = $temp;
//
//                foreach($addresses as $address){
//                    if($address['mid'] == $item->id) {
//                        $item->default_address = $address;
//                    }
//                }
//            }
//        }
//
//        if ($rows) {
//            $rows = $rows->toArray();
//            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), $pageLength);
//        }
//
//        $txtStr['status'] = [0 => '禁用', 1 => '正常'];
//        $rows['data'] = int_to_string($rows['data'], $txtStr);
//        return $rows;
//    }

    public function getMemberList()
    {
        $keyword = request('keyword');
        $type = request('type', 0);
        $memberfields = 'id,admin_id,shop_id,nickname,avatarurl,wx_openid,status,total_waterbill_num,initial_bucket_num,self_bucket_num,total_bucket_num,
        total_back_bucket_num,cash_bucket_num,borrow_bucket_num,deposit,import_bucket,import_waterbill,created_at,refer_type,worker_id';
        $workerFields = 'id,shop_id,name';
//        $cashFields = 'id,lose_pay,self_bucket,cash_bucket,cash,water_dispenser,water_dispenser_cash,status,description,mid';
        $billFields = 'goods_name,rest_num,mid';
        $addressFields = 'id,shop_id,name,type,mobile,address,position_address,company_name,mid';
        $pageSize = 15;
        $pageLength = 10;
        $where = [];
        $relations[] = 'memberWaterBill';
        $relations_columns['memberWaterBill'] = $billFields;
        if (session('shop_info')) {
            if (session('shop_info.send_mode') == 2) {
                $relations[] = 'worker';
                $relations_columns['worker'] = $workerFields;
            }
        }
        $relations_wheres = [];
        $order = ['id'=>'asc'];
        $flag = 0;
        if ($keyword && $type) {
            if ($type != 1) {
                $flag = 1;
                $relations[] = 'member';
                $relations_columns['member'] = $memberfields;
                switch ($type) {
                    case 2:
                        $where = ['name' => ['like', "%{$keyword}%"]];
                        break;
                    case 3:
                        $where = ['mobile' => ['like', "%{$keyword}%"]];
                        break;
                    case 4:
                        $where = ['company_name' => ['like', "%{$keyword}%"]];
                        break;
                    case 5:
                        $where = ['address' => ['like', "%{$keyword}%"]];
                        break;
                }
            } else {
                $where['id'] = $keyword;
            }
        }
        if (!is_administrator()) {
            if (plat_identify() == 'admin') {
                $where['admin_id'] = plat_admin_id();
            } else {
                $where['shop_id'] = session('account.shop_id');
            }
        }
        if ($flag) {
            $address = new Address();
            $order = ['mid'=>'asc'];
            $relations = ['memberWaterBill','member'];
            $rows = $address->_getJionMorePageList($relations, $where, $relations_wheres, $addressFields, $relations_columns, $order, $pageSize, $pageLength);
            $worker = new Worker();
            if ($rows['data']) {
                $arr = [];
                foreach ($rows['data'] as $k=>$v) {
                    if(!$v['member']) {
                        unset($rows['data'][$k]);
                        continue;
                    } else {
                        $tem = $v['member'];
                        $tem['address'] = [
                            "id" => $v['id'],
                            "name" => $v['name'],
                            "type" => $v['type'],
                            "mobile" => $v['mobile'],
                            "address" => $v['address'],
                            "company_name" => $v['company_name'],
                            "position_address" => $v['position_address']
                        ];
//                    $tem['cash'] = $v['cash'];
                        $tem['member_water_bill'] = $v['member_water_bill'];
                        $tem['worker'] = [];
                        if ($v['member']['worker_id']) {
                            $tem['worker'] = $worker->_redisGetOneByWid($v['member']['worker_id']);
                        }
                        $arr[] = $tem;
                    }
                }
                $rows['data'] = $arr;
            }
        } else {
            $relations[] = 'address';
            $relations_columns['address'] = $addressFields;
            $relations_wheres = ['address' => ['is_default' => 1]];
            $rows = $this->_getJionMorePageList($relations, $where, $relations_wheres, $memberfields, $relations_columns, $order, $pageSize, $pageLength);
        }
        $txtStr['status'] = [0 => '禁用', 1 => '正常'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getMemberListWithCash()
    {
        $keyword = request('keyword');
        $buyer_name = request('buyer_name');
        $start = request('time-start');
        $end = request('time-end');
        $where['admin_id'] = plat_admin_id();
        request('shop_id') && $where['shop_id'] = request('shop_id');
        request('status') && $where['status'] = request('status');
        $keyword && $where['mobile'] = $keyword;
        $buyer_name && $where['buyer_name'] = ['like', '%' . $buyer_name . '%'];
        if ($start && !$end) {
            $where['addtime'] = ['>=', strtotime($start)];
        }
        if ($end && !$start) {
            $where['addtime'] = ['<=', strtotime($end)];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        $rows = $this->_getJoinPageList('orderGoods', $where, '*', ['id' => 'desc'], 10, 5, '*', ['admin_id' => $where['admin_id']]);
        $txtStr['status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['type'] = [0 => '在线支付', 1 => '线下支付'];
        $txtStr['dispatch'] = [1 => '正在派送', 2 => '已完成', 0 => '未派送', -1 => '过期超时'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    /**
     * 注册一个新用户
     * @param  string $username 用户名
     * @param  string $password 用户密码
     * @param  string $email 用户邮箱
     * @param  string $mobile 用户手机号码
     * @return integer          注册成功-用户信息，注册失败-错误编号
     */
    public function register($username, $password, $email, $mobile)
    {
        $data = [
            'username' => $username,
            'password' => $password,
            'email' => $email,
            'mobile' => $mobile,
        ];

        //验证手机
        if (empty($data['mobile'])) unset($data['mobile']);

        $validator = Validator::make($data, $this->_validate);

        //验证失败
        if ($validator->fails()) {
            //返回所有错误信息
            return $validator->errors()->all();
        }
        $data['password'] = md5($data['password']);
        $data['reg_time'] = time();
        $data['reg_ip'] = request()->ip();
        $data['update_time'] = time();
        $data['reg_time'] = time();
        $data['status'] = 1;
        /* 添加用户 */
        $uid = $this->_add($data);
        return $uid ? $uid : 0; //0-未知错误，大于0-注册成功
    }

    /**
     * 用户登录认证
     * @param  string $username 用户名
     * @param  string $password 用户密码
     * @param  integer $type 用户名类型 （1-用户名，2-邮箱，3-手机，4-UID）
     * @return integer           登录成功-用户ID，登录失败-错误编号
     */
    public function login($request, $type = 1)
    {
        $username = $request['username'];
        $password = $request['password'];
        $where = array();
        switch ($type) {
            case 1:
                $where['username'] = $username;
                break;
            case 2:
                $where['email'] = $username;
                break;
            case 3:
                $where['mobile'] = $username;
                break;
            case 4:
                $where['id'] = $username;
                break;
            default:
                return 0; //参数错误
        }

        /* 获取用户数据 */
        $admin = $this->_getOne($where);
        if (!$admin || $admin['status'] != 1) {
            $this->error = '用户不存在或已被禁用！'; //应用级别禁用
            return false;
        }
        /* 验证用户密码 */
        if (md5($password) !== $admin['password']) {
            $this->error = '账号或密码错误';
            return false;
        }
        $this->updateLogin($admin); //更新用户登录信息
        $menu = new Menu();
        session(['menus' => $menu->getMenus()]);
        session()->save();
        //记录行为
        $actionLog = new ActionLog();
        $actionLog->action_log('admin_login', 'admin', $admin['id'], $admin['id']);
        return true;
    }


    /**
     * 获取用户信息
     * @param  string $uid 用户ID或用户名
     * @param  boolean $is_username 是否使用用户名查询
     * @return array                用户信息
     */
    public function info($uid, $is_username = false)
    {
        $where = [];
        if ($is_username) { //通过用户名获取
            $where['username'] = $uid;
        } else {
            $where['id'] = $uid;
        }

        $admin = $this->_getOne($where, 'id,username,email,mobile,status');
        if (is_array($admin) && $admin['status'] == 1) {
            return [$admin['id'], $admin['username'], $admin['email'], $admin['mobile']];
        } else {
            return -1; //用户不存在或被禁用
        }
    }

    /**
     * 检测用户信息
     * @param  string $field 用户名
     * @param  integer $type 用户名类型 1-用户名，2-用户邮箱，3-用户电话
     * @return integer         错误编号
     */
    public function checkField($field, $type = 1)
    {
        $data = [];
        switch ($type) {
            case 1:
                $data['username'] = $field;
                break;
            case 2:
                $data['email'] = $field;
                break;
            case 3:
                $data['mobile'] = $field;
                break;
            default:
                return 0; //参数错误
        }
        $validator = Validator::make($data, $this->_validate);
        //验证失败
        if ($validator->fails()) {
            //返回所有错误信息
            return $validator->errors()->all();
        }
        return true;
    }

    /**
     * 更新用户登录信息
     * @param  integer $uid 用户ID
     */
    protected function updateLogin($user)
    {
        /* 更新登录信息 */
        $data = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip()
        ];
        $this->_inc(['id' => $user['id']], 'login', 1, $data);

        /* 记录登录SESSION和COOKIES */
        $auth = [
            'uid' => $user['id'],
            'username' => $user['username'],
            'last_login_time' => $user['last_login_time'],
        ];
        session(['user_auth' => $auth]);
        session(['user_auth_sign' => data_auth_sign($auth)]);
    }

    /**
     * 更新用户信息
     * @param int $uid 用户id
     * @param string $password 密码，用来验证
     * @param array $data 修改的字段数组
     * @return true 修改成功，false 修改失败
     */
    public function updateUserFields($uid, $password, $data)
    {
        if (empty($uid) || empty($password) || empty($data)) {
            $this->error = '参数错误！';
            return false;
        }

        //更新前检查用户密码
        if (!$this->verifyUser($uid, $password)) {
            $this->error = '验证出错：密码不正确！';
            return false;
        }
        $validator = Validator::make($data, $this->_validate);
        //验证失败
        if ($validator->fails()) {
            //返回所有错误信息
            return false;
        }
        //更新用户信息
        return $this->_update(['id' => $uid], $data);
    }

    /**
     * 验证用户密码
     * @param int $uid 用户id
     * @param string $password_in 密码
     * @return true 验证成功，false 验证失败
     */
    public function verifyUser($uid, $password_in)
    {
        $password = $this->_getOne(['id' => $uid], 'password');
        if (md5($password_in) === $password) {
            return true;
        }
        return false;
    }

    public function getAdminList()
    {
        $nickname = request('nickname');
        $where['status'] = ['>=', 0];
        if (is_numeric($nickname)) {
            $where['uid'] = $nickname;
        } else {
            $where['nickname'] = ['like', '%' . $nickname . '%'];
        }
        $rows = $this->_getPageList($where);
        return int_to_string($rows);
    }

    public function import($shopId, $adminId)
    {
        $mid = request('mid');
        $type = request('type', 0);
        $bucket_category = intval(request('bucket_category_id'));
        $self_bucket_category = intval(request('self_bucket_category_id'));
        $totle_bucket_num = intval(request('bucket_num'));
//        $self_bucket_num = intval(request('self_bucket_num'));
        $bucket_num = $totle_bucket_num;
        $current_time = time();

        $waterbill_id = intval(request('waterbill_id'));
        $waterbill_num = intval(request('waterbill_num'));
//        dd($mid,$type,$bucket_category,$self_bucket_category,$bucket_num,$self_bucket_num,$waterbill_id,$waterbill_num);
        $data['shop_id'] = $shopId;
        $member = $this->_getOneById($mid);
        $this->_start();
        try {
            $memberData['id'] = $mid;
            if (!$type) {
                if ($member['import_bucket']) {
                    $this->_rollBack();
                    $this->error = '该客户已导入';
                    return false;
                }
                if (!$bucket_num) {
                    $this->error = '水桶数量不能为0';
                    $this->_rollBack();
                    return false;
                }
                $memberData['initial_bucket_num'] = $bucket_num;
                $memberData['initial_bucket_category'] = $bucket_category;
                $memberData['self_bucket_category'] = $self_bucket_category;
//                $memberData['self_bucket_num'] = $self_bucket_num;
                $memberData['borrow_bucket_num'] = $bucket_num + $member['total_bucket_num'] - $member['total_back_bucket_num'] - $member['cash_bucket_num'] - $member['self_bucket_num'];
                $memberData['import_bucket'] = 1;
                //更新用户水桶信息qds_member
                $a = $this->_save($memberData);
                if (!$a) {
                    $this->error = '更新用户水桶信息失败';
                    $this->_rollBack();
                    return false;
                }
                //更新店铺水桶信息qds_shop
//                $shop = new Shop();
//                $b = $shop->_inc(['id' => $shopId], 'total_bucket_num', $bucket_num);
//                if (!$b) {
//                    $this->error = '更新用户水桶信息失败';
//                    $this->_rollBack();
//                    return false;
//                }
                //更新店铺水桶品牌信息qds_bucket_data
                $bucketData = new BucketData();
                $where['shop_id'] = $shopId;
                $where['bucket_category_id'] = $bucket_category;
                $c = $bucketData->_inc($where, 'bucket_num_out', $bucket_num);
                if (!$c) {
                    $this->error = '更新水桶统计信息失败';
                    $this->_rollBack();
                    return false;
                }
                $logData = [
                    'order_id' => 0,
                    'shop_id' => $shopId,
                    'worker_id' => request('wid', 0),
                    'buyer_id' => $mid,
                    'buyer_name' => $member['name'],
                    'send_num' => $totle_bucket_num,
                    'bucket_num' => 0,
                    'description' => '导入初始',
                    'addtime' => $current_time,
                ];
//                tolog($logData);
                $buckLog = new BucketLog();
                $logId = $buckLog->_save($logData); //(8)
//                tolog('buckLog------'.$logId);
                $backLogData = new BackLogData();
                $backData['log_id'] = $logId;
                $backData['bucket_category_id'] = $bucket_category;
                $backData['num'] = $bucket_num;
                $backData['shop_id'] = $shopId;
                $backData['worker_id'] = request('wid', 0);
                $backData['buyer_id'] = $mid;
//                tolog($backData);
                $res = $backLogData->_save($backData);
//                tolog('backLogData------'.$res);
            } else {
                if ($member['import_waterbill']) {
                    $this->error = '该客户已导入';
                    $this->_rollBack();
                    return false;
                }
                if (!$waterbill_num) {
                    $this->error = '水票数量不能为0';
                    $this->_rollBack();
                    return false;
                }
                $memberData['total_waterbill_num'] = $member['total_waterbill_num'] + $waterbill_num;
                $memberData['import_waterbill'] = 1;
                //更新用户水票信息qds_member
                $a = $this->_save($memberData);
                if (!$a) {
                    $this->_rollBack();
                    $this->error = '更新用户水桶信息失败4';
                    return false;
                }
                //更新用户水票信息qds_member_waterbill
                $memberBill = new MemberWaterBill();
                $bill = $memberBill->_getOne(['mid' => $mid, 'waterbill_id' => $waterbill_id]);
                if (!$bill) {
                    //没有水票信息则添加
                    $a = $memberBill->importBill($member, $shopId, $waterbill_id, $waterbill_num);
                    if (!$a) {
                        $this->_rollBack();
                        $this->error = $memberBill->getError();
                        return false;
                    }
                } else {
                    //有水票信息则更新
                    $billData['id'] = $bill['id'];
                    $billData['rest_num'] = $bill['rest_num'] + $waterbill_num;
                    $a = $memberBill->_save($billData);
                    if (!$a) {
                        $this->_rollBack();
                        $this->error = '更新水票信息失败';
                        return false;
                    }
                }
                //更新店铺总水票信息qds_shop
//                $shop = new Shop();
//                $a = $shop->_inc(['id' => $shopId], 'total_water_bill_num', 1);
//                if (!$a) {
//                    $this->_rollBack();
//                    $this->error = '更新店铺总水票信息信息失败';
//                    return false;
//                }
                //更新店铺水票销量信息qds_shop
                $waterBill = new WaterBill();
//                $a = $waterBill->_inc(['id' => $waterbill_id], 'sale_num');
//                if (!$a) {
//                    $this->_rollBack();
//                    $this->error = '更新店铺水票销量信息失败';
//                    return false;
//                }
                //  记录水票消费日志
                $info = $waterBill->_getOneById($waterbill_id);
                $order['order_sn'] = makeOrderSn($mid);
                $order['admin_id'] = $adminId;
                $order['shop_id'] = $shopId;
                $order['mid'] = $mid;
                $order['waterbill_id'] = $waterbill_id;
                $order['goods_id'] = $info['goods_id'];
                $order['goods_name'] = $info['goods_name'];
                $order['goods_num'] = $waterbill_num;
                $order['order_amount'] = 1;
                $billLog = new MemberWaterBillLog();
                $order['buyer_id'] = $order['mid'];
                $order['bill_id'] = $order['waterbill_id'];
                $e = $billLog->log($order, $order, 4);
                if (!$e) {
                    $this->_rollBack();
                    $this->error = $billLog->getError();
                    return false;
                }
                $memberBill->_redisGenerateBillListByMid($mid);

                // 生成订单
                unset($order['goods_num']);
                unset($order['buyer_id']);
                unset($order['bill_id']);
                $order['shop_goods_id'] = $info['shop_goods_id'];
                $order['brand_id'] = $info['brand_id'];
                $order['bucket_category_id'] = $info['bucket_category_id'];
                $order['category_id'] = $info['category_id'];
                $order['goods_price'] = $info['goods_price'];
                $order['buy_num'] = $waterbill_num;
                $order['total_num'] = $waterbill_num;
                $order['order_amount'] = bcmul($info['goods_price'], $waterbill_num, 2);
                $order['type'] = 1;
                $order['status'] = 1;
                $order['rest_num'] = $waterbill_num;
                $order['pay_status'] = 20;
                $order['addtime'] = $current_time;
                $order['title'] = '老用户导入';

                $waterBillOrder = new WaterBillOrder();
                $res = $waterBillOrder->_save($order);
                if(!$res) {
                    $this->_rollBack();
                    $this->error = $waterBillOrder->getError();
                    return false;
                }
            }
            $this->_commit();
            return true;
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '导入失败';
            return false;
        }

    }

    public function charge($waterbill_id, $waterbill_num, $mid, $shop_id, $money, $workerInfo = [])
    {
        if (!$waterbill_id) {
            $this->error = '非法操作';
            return false;
        }
        if (!$waterbill_num) {
            $this->error = '水票数量不能为0';
            return false;
        }
        if (!$mid) {
            $this->error = '非法操作';
            return false;
        }
        if (!$shop_id) {
            $this->error = '非法操作';
            return false;
        }
//        if (!$money) {
//            $this->error = '金额不能为0';
//            return false;
//        }
        $member = $this->_getOneById($mid);
        if (!$member) {
            $this->error = '非法操作';
            return false;
        }
        $this->_start();
        try {
            $memberData['id'] = $mid;
            $memberData['total_waterbill_num'] = $member['total_waterbill_num'] + $waterbill_num;
            //更新用户水票信息qds_member
            $a = $this->_save($memberData);
            if (!$a) {
                $this->_rollBack();
                $this->error = '更新用户水桶信息失败';
                return false;
            }
            $waterBill = new WaterBill();
            $info = $waterBill->_getOneById($waterbill_id);
            if (!$info) {
                $this->_rollBack();
                $this->error = '获取水票信息失败';
                return false;
            }

            //更新用户水票信息qds_member_waterbill
            $memberBill = new MemberWaterBill();
            $bill = $memberBill->_getOne(['mid' => $mid, 'shop_goods_id' => $info['shop_goods_id']]);
            if (!$bill) {
                //没有水票信息则添加
                $a = $memberBill->importBill($member, $shop_id, $waterbill_id, $waterbill_num);
                if (!$a) {
                    $this->_rollBack();
                    $this->error = $memberBill->getError();
                    return false;
                }
            } else {
                //有水票信息则更新
                $billData['id'] = $bill['id'];
                $billData['rest_num'] = $bill['rest_num'] + $waterbill_num;
                $a = $memberBill->_save($billData);
                if (!$a) {
                    $this->_rollBack();
                    $this->error = '更新水票信息失败';
                    return false;
                }
            }
            //更新店铺总水票信息qds_shop
//            $shop = new Shop();
//            $a = $shop->_inc(['id' => $shop_id], 'total_water_bill_num', 1);
//            if (!$a) {
//                    $this->_rollBack();
//                $this->error = '更新店铺总水票信息信息失败';
//                    return false;
//            }
            //更新店铺水票销量信息qds_shop
//            $a = $waterBill->_inc(['id' => $waterbill_id], 'sale_num');
//            if (!$a) {
//                    $this->_rollBack();
//                $this->error = '更新店铺水票销量信息失败';
//                    return false;
//            }
            //  记录水票消费日志
            $order['order_sn'] = makeOrderSn($mid);
            $order['admin_id'] = plat_admin_id();
            $order['shop_id'] = $shop_id;
            $order['mid'] = $mid;
            $order['waterbill_id'] = $waterbill_id;
            $order['goods_id'] = $info['goods_id'];
            $order['goods_name'] = $info['goods_name'];
            $order['goods_num'] = $waterbill_num;
            $order['order_amount'] = $money;
            $billLog = new MemberWaterBillLog();
            $order['buyer_id'] = $order['mid'];
            $order['bill_id'] = $order['waterbill_id'];
            $e = $billLog->log($order, $order, 5);
            if (!$e) {
                $this->_rollBack();
                $this->error = $billLog->getError();
                return false;
            }
            $adminInfo = session(session('platIdentify'));
            if ($adminInfo && !$workerInfo) {
                $adminName = isset($adminInfo['username']) ? $adminInfo['username'] : '';
            }
            // 水票充值订单记录
            $time = time();
            $waterBillOrder = new WaterBillOrder();
            $data['order_sn'] = makeOrderSn($mid);
            $data['admin_id'] = $info['admin_id'];
            $data['shop_id'] = $info['shop_id'];
            $data['mid'] = $mid;
            $data['waterbill_id'] = $waterbill_id;
            $data['brand_id'] = $info['brand_id'];
            $data['bucket_category_id'] = $info['bucket_category_id'];
            $data['category_id'] = $info['category_id'];
            $data['shop_goods_id'] = $info['shop_goods_id'];
            $data['goods_id'] = $info['goods_id'];
            $data['goods_name'] = $info['goods_name'];
            $data['goods_price'] = $info['goods_price'];
            $data['order_amount'] = $money;
            $data['buy_num'] = $waterbill_num;
            $data['total_num'] = $waterbill_num;
            $data['type'] = 1;
            $data['status'] = 1;
            $data['rest_num'] = $waterbill_num;
            $data['pay_status'] = 20;
            $data['payment_time'] = $time;
            $data['addtime'] = $time;
            $data['title'] = '人工充值'.($workerInfo ? '<br/>配送员【'.$workerInfo['name'].'】' : '<br/>管理员【'.$adminName.'】');
            $o = $waterBillOrder->_save($data);
            if(!$o){
                $this->_rollBack();
                $this->error = $waterBillOrder->getError();
                return false;
            }

            $this->_commit();
            $memberBill->_redisGenerateBillListByMid($mid);
            return true;
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '充值失败';
            return false;
        }

    }

    public function move()
    {
        $mid = $GLOBALS['mid'];
        $admin_id = $GLOBALS['admin_id'];
        $xcx_openid = $GLOBALS['xcx_openid'];
        $wx_openid = $GLOBALS['wx_openid'];
        $shop_id = $GLOBALS['shop_id'];
        $captcha = request('captcha');
        $data['id'] = trim($mid);
        $data['name'] = trim(request('name'));
        $data['mobile'] = trim(request('mobile'));
        if (!$data['id']) {
            $this->error = '请输入受移交人ID';
            return false;
        }
        if (!$captcha) {
            $this->error = '请输入验证码';
            return false;
        }
        if (!$data['name']) {
            $this->error = '请输入受移交人姓名';
            return false;
        }
        if (!$data['mobile']) {
            $this->error = '请输入受移交人手机号';
            return false;
        }
        if (!is_mobile($data['mobile'])) {
            $this->error = '请输入正确手机号';
            return false;
        }
        $info = $this->_getOne(['id' => $mid]);
        if (!$info['mobile']) {
            $this->error = '非法操作!';
            return false;
        }
        $smsLog = new SmsLog();
        $res = $smsLog->checkSmsCaptcha($info['mobile'], $captcha, 1);
        if (!$res['status']) {
            $this->error = $res['msg'];
            return false;
        }
        $where['id'] = intval(trim(request('move_id')));
        $where['admin_id'] = intval(trim($admin_id));
        $where['shop_id'] = $shop_id;
        $memberInfo = $this->_getOne($where);
        if (!$memberInfo) {
            $this->error = '该受移交人ID不存在!';
            return false;
        }
        if (!($memberInfo['xcx_openid'] && !is_numeric($memberInfo['xcx_openid']))) {
            $this->error = '该受移交人没有授权微信信息无法移交!';
            return false;
        }
        $initBucketNum = $memberInfo['initial_bucket_num'] ? $memberInfo['initial_bucket_num'] : $memberInfo['self_bucket_num'];
        $totleBucket = $initBucketNum + $memberInfo['total_bucket_num'] - $memberInfo['total_back_bucket_num'];
        if ($totleBucket || intval($memberInfo['deposit']) || $memberInfo['total_waterbill_num']) {
            $this->error = '受移交人微信号已关联的账户中有未处理的水桶/押金/水票信息，无法迁移!';
            return false;
        }
        $data['xcx_openid'] = $memberInfo['xcx_openid'];
        $data['wx_openid'] = $memberInfo['wx_openid'];
        $data['unionid'] = $memberInfo['unionid'];
        $data['nickname'] = $memberInfo['nickname'];
        $data['avatarurl'] = $memberInfo['avatarurl'];
        $this->_start();
        try {
            $this->_del(['id' => $where['id']]);
            $this->_save($data);
            $this->_commit();
            //清除双方xcx_openid缓存
            $key = $info['xcx_openid'] . '_' . $shop_id;
            $this->redis->del($key);
            $key1 = $memberInfo['xcx_openid'] . '_' . $shop_id;
            $this->redis->del($key1);
            //清除双方wx_openid缓存
            $key2 = $info['wx_openid'] . '_' . $shop_id;
            $this->redis->del($key2);
            $key3 = $memberInfo['wx_openid'] . '_' . $shop_id;
            $this->redis->del($key3);
            return '移交成功';
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '迁移交失败!';
            return false;
        }
    }

    public function yijiao($mid, $moveId, $admin_id, $shop_id)
    {
        $info = $this->_getOne(['id' => $mid]);
        if (!$info) {
            $this->error = '非法操作!';
            return false;
        }
        $where['id'] = trim($moveId);
        $where['admin_id'] = trim($admin_id);
        $where['shop_id'] = $shop_id;
        $memberInfo = $this->_getOne($where);
        if (!$memberInfo) {
            $this->error = '该受移交人ID不存在!';
            return false;
        }
        if (is_numeric($memberInfo['xcx_openid']) || is_numeric($memberInfo['wx_openid'])) {
            $this->error = '该受移交人没有授权微信信息无法移交!';
            return false;
        }
        $initBucketNum = $memberInfo['initial_bucket_num'] ? $memberInfo['initial_bucket_num'] : $memberInfo['self_bucket_num'];
        $totleBucket = $initBucketNum + $memberInfo['total_bucket_num'] - $memberInfo['total_back_bucket_num'];
        if ($totleBucket || intval($memberInfo['deposit']) || $memberInfo['total_waterbill_num']) {
            $this->error = '受移交人微信号已关联的账户中有未处理的水桶/押金/水票信息，无法迁移!';
            return false;
        }
        $data['id'] = intval($mid);
        $data['xcx_openid'] = $memberInfo['xcx_openid'];
        $data['wx_openid'] = $memberInfo['wx_openid'];
        $data['unionid'] = $memberInfo['unionid'];
        $data['nickname'] = $memberInfo['nickname'];
        $data['avatarurl'] = $memberInfo['avatarurl'];
        $data['name'] = $memberInfo['name'];
        $data['mobile'] = $memberInfo['mobile'];
        $this->_start();
        try {
            $this->_del(['id' => $where['id']]);
            $this->_save($data);
            $this->_commit();
            $key = $info['xcx_openid'] . '_' . $shop_id;
            $key1 = $memberInfo['xcx_openid'] . '_' . $shop_id;
            $key2 = $info['wx_openid'] . '_' . $shop_id;
            $key3 = $memberInfo['wx_openid'] . '_' . $shop_id;
            $this->redis->del($key);
            $this->redis->del($key1);
            $this->redis->del($key2);
            $this->redis->del($key3);
            return '移交成功';
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '迁移交失败!';
            return false;
        }
    }

    public function _redisGetOneByXcxOpenId($xcx_openid, $shop_id)
    {
        $key = $xcx_openid . '_' . $shop_id;
        if ($this->redis->exists($key)) {
            $res = $this->redis->get($key);
            if ($res) {
                return unserialize($res);
            }
        }
        $res = $this->_getOne(['xcx_openid' => $xcx_openid, 'shop_id' => $shop_id], 'id as mid,shop_id as sid,xcx_openid,nickname,avatarurl,admin_id as aid,mobile,status');
        if ($res) {
            $res = $res->toArray();
            $this->redis->setex($key, 3600, serialize($res));;
        }
        return $res;
    }

    public function _redisGetOneByWxOpenId($wx_openid, $shop_id)
    {
        $key = $wx_openid . '_' . $shop_id;
        if ($this->redis->exists($key)) {
            $res = $this->redis->get($key);
            if ($res) {
                return unserialize($res);
            }
        }
        $res = $this->_getOne(['wx_openid' => $wx_openid, 'shop_id' => $shop_id], 'id as mid,shop_id as sid,wx_openid,nickname,avatarurl,admin_id as aid,mobile,status,is_default,worker_id');
        if ($res) {
            $res = $res->toArray();
            $this->redis->setex($key, 3600, serialize($res));
        }
        return $res;
    }

    public function _redisGenerateByXcxOpenId($xcx_openid, $shop_id)
    {
        $key = $xcx_openid . '_' . $shop_id;
        if ($this->redis->exists($key)) {
            $this->redis->del($key);
        }
    }

    public function _redisGenerateByOpenId($ids, $shop_id)
    {
        foreach($ids as $v) {
            $memberInfo = $this->_redisGetOneByMid($v);
            if ($memberInfo['xcx_openid']) {
                $key = $memberInfo['xcx_openid'] . '_' . $shop_id;
                if ($this->redis->exists($key)) {
                    $this->redis->del($key);
                }
            }
            if ($memberInfo['wx_openid']) {
                $key = $memberInfo['wx_openid'] . '_' . $shop_id;
                if ($this->redis->exists($key)) {
                    $this->redis->del($key);
                }
            }

        }
    }

    public function addOrUpdate($admin_id, $shopId)
    {
        if (!($admin_id && $shopId)) {
            $this->error = '非法操作';
            return false;
        }
        $data['admin_id'] = $admin_id;
        $data['shop_id'] = $shopId;
        $data['is_default'] = 1;
        $data['name'] = trim(request('name'));
        $data['address'] = trim(request('address'));
        $data['province_id'] = request('province');
        $data['city_id'] = request('city', 0);
        $data['area_id'] = request('area');
        $data['area_info'] = request('area_info');
        $data['company_name'] = trim(request('company_name'));
        $data['type'] = trim(request('type'));
        $data['mobile'] = trim(request('mobile'));

        // 北京 110000 天津 120000 上海 310000 重庆 500000 香港 810000 澳门 820000
        $special = [
            110000, 120000, 310000, 500000, 810000, 820000
        ];
        // 排除 直辖市及香港、澳门特别行政区
        if (!in_array($data['province_id'], $special)) {
            if (!$data['city_id'] || !$data['area_id']) {
                $this->error = '请选择所属地区';
                return false;
            }
        } else {
            if (!$data['area_id']) {
                $this->error = '请选择所属地区';
                return false;
            }
        }
        if (!$data['name']) {
            $this->error = '请填写用户姓名';
            return false;
        }
        if (!$data['mobile']) {
            $this->error = '请填写联系方式';
            return false;
        }
        if ($data['type'] == 1 && !$data['company_name']) {
            $this->error = '请填写单位名称';
            return false;
        }
        if (!$data['area_info']) {
            $this->error = '请选择所属地区';
            return false;
        }
        if (!$data['address']) {
            $this->error = '请填写门牌号';
            return false;
        }
        if(!request('area_position') || !request('area_position')) {
            $this->error = '请选择地址';
            return false;
        }
        if (request('id')) {
            $data['id'] = request('id');
        } else {
            $data['addtime'] = time();
            $data['xcx_openid'] = $data['addtime'];
        }

        $address = new Address();
        // 新增时判断用户是否有收货地址
        if(!request('address_id')) {
            $where['name'] = $data['name'];
            $where['mobile'] = $data['mobile'];
            $where['shop_id'] = $shopId;
            $where['mid'] = ['<>', request('id')];
            $res = $address->_getOne($where,'id,mid');
            if ($res) {
                $this->error = '该用户已存在';
                return false;
            }
        }

        $this->_start();
        try {
            $res = $this->_save($data);
            if(!$res) {
                $this->_rollBack();
                $this->error = '操作失败';
                return false;
            }
            $res && $data['id'] = $res;

            $address = new Address();
            $addressData = $data;

            if (request('address_id')) {
                $addressData['id'] = request('address_id');
            }else {
                if(isset($addressData['id'])) {
                    unset($addressData['id']);
                }
            }
            $addressData['position_address'] = trim(request('position_address',''));
            $addressData['area_position'] = request('area_position');
            $addressData['mid'] = $data['id'];
            unset($addressData['xcx_openid']);
            unset($addressData['addtime']);
            $address->_save($addressData);

            $bill_id = intval(request('bill_id'));
            $bill_num = intval(request('waterbill_num'));
            if($bill_id && !$bill_num) {
                $this->_rollBack();
                $this->error = '请填写水票数量';
                return false;
            }
            if($bill_id && $bill_num) {
                $res = $this->charge($bill_id, $bill_num, $data['id'], $shopId, 0);
                if(!$res) {
                    $this->_rollBack();
                    $this->error = '导入水票失败';
                    return false;
                }
            }

            $this->_commit();
            return true;
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = request('id') ? '编辑用户失败' : '新增用户失败';
            return false;
        }
    }

    public function _redisGenerateByMid($mid)
    {
        $table = $this->redisTable;
        $key = $mid;
        $this->redis->hdel($table, $key);
    }

    public function _redisGetOneByMid($mid)
    {
        $table = $this->redisTable;
        $key = $mid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                return unserialize($res[0]);
            }
        }
        $res = $this->_getOneById($mid, 'wx_openid,xcx_openid');
        if ($res) {
            $res = $res->toArray();
            $this->redis->hmset($table, [$key => serialize($res)]);
        }
        return $res;
    }

    public function _redisSetFormId($mid, $formId)
    {
        if (!($formId && $mid)) {
            return false;
        }
        $table = 'form_id_list';
        $key = $mid;
        $formIds = [];
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                $formIds = unserialize($res[0]);
            }
        }
        if (!empty($formIds)) {
            if (count($formIds) >= 10) {
                return true;
            }
            array_push($formIds, $formId);
        } else {
            $formIds[] = $formId;
        }
        $arr = array_values($formIds);
        return $this->redis->hmset($table, [$key => serialize($arr)]);
    }

    public function _redisGetFormId($mid)
    {
        if (!$mid) {
            return false;
        }
        $table = 'form_id_list';
        $key = $mid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                $res = unserialize($res[0]);
                if (!empty($res)) {
                    $formId = $res[0];
                    unset($res[0]);
                    $newRes = array_values($res);
                    $this->redis->hmset($table, [$key => serialize($newRes)]);
                    return $formId;
                }
                return false;
            }
        }
        return false;
    }

    public function addWxMemberWithWxOpenId($aid, $baseInfo, $shopId = 0, $refer_mid = 0)
    {
        if(!$shopId) {
            $shops = (new Shop())->_getList(['admin_id'=>$aid])->toArray();
            if(count($shops) == 1){
                $shopId = $shops[0]['id'];
            }
        }

        $memberInfo = $this->_getOne(['wx_openid' =>$baseInfo['openid'], 'shop_id' => $shopId]);
        if(!$memberInfo) {
            $key = md5($baseInfo['openid']);
            if($this->redis->get($key)) {
                $memberData = unserialize($this->redis->get($key));
            } else {
                $memberData = [
                    'shop_id' => $shopId,
                    'admin_id' => $aid,
                    'wx_openid' => $baseInfo['openid'],
                    'nickname' => $baseInfo['nickname'],
                    'avatarurl' => $baseInfo['headimgurl'],
                    'addtime' => time(),
                    'is_default' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                if(!$shopId){
                    $this->redis->setex($key,3600, serialize($memberData));
                }
            }

            if($refer_mid) {
                $memberData['refer_mid'] = $refer_mid;
                // 判断推广员ID下是否有佣金信息存在
                $commissionInfo = (new MemberCommission())->_getOne(['mid' => $refer_mid]);
                if(!$commissionInfo) {
                    $data = [
                        'mid' => $refer_mid,
                        'shop_id' => $shopId,
                        'admin_id' => $aid,
                        'total_member' => 1
                    ];
                } else {
                    $data['total_member'] = $commissionInfo['total_member'] + 1;
                    $data['id'] = $commissionInfo['id'];
                }
                $resC = (new MemberCommission())->_save($data);
                if(!$resC) {
                    return false;
                }
            }



            $this->_start();
            try {
                $resM = $this->_save($memberData);
                if(!$resM) {
                    $this->_rollBack();
                    return false;
                }
                $upWhere['id'] = ['<>', $resM];
                $upWhere['wx_openid'] = $memberInfo['wx_openid'];
                $this->_update($upWhere, ['is_default' => 0]);
                $this->_redisGetOneByWxOpenId($baseInfo['openid'],$shopId);
                $this->_commit();
                return true;
            } catch (\Exception $e) {
                $this->_rollBack();
                return false;
            }
        }

        return true;
    }

    public function getMemberInfoByOpenId($xcx_openid, $wx_openid, $shopId)
    {
        if($xcx_openid || $wx_openid) {
            if($xcx_openid) {
                $memberInfo = $this->_redisGetOneByXcxOpenId($xcx_openid, $shopId);
            } else {
                $memberInfo = $this->_redisGetOneByWxOpenId($wx_openid, $shopId);
            }
            return $memberInfo;
        }
        return false;
    }

    public function updateMemberBuy()
    {
        $id = request('id');
        $member = $this->_getOneById($id);
        if(!$member){
            $this->error = '用户不存在';
            return false;
        }
        $data['buy_min'] = request('buy_min');
        $data['buy_max'] = request('buy_max');
        if(!$data['buy_min'] || !$data['buy_max']){
            $this->error = '请输入购买下限或购买上限';
            return false;
        }
        if($data['buy_min'] > $data['buy_max']){
            $this->error = '购买下限不能超过购买上限';
            return false;
        }
        $res = $this->_update(['id' => $id],$data);
        if(!$res) {
            $this->error = '更新用户购买数量失败';
            return false;
        }
        return true;
    }

    // 更新默认店铺
    public function changeMemberDefault($res, $wxOpenId, $sid, $referMid)
    {
        if($res) {
            $memberInfo = $this->_redisGetOneByWxOpenId($wxOpenId,$sid);
            $shop = (new Shop())->_redisGetOneBySid($sid);
            $content = '欢迎进入店铺【'.$shop['shop_name'].'】';

            if($this->redis->get($wxOpenId)) {
                $content = '您已绑定店铺【'.$shop['shop_name'].'】，';
                $referMember = $this->_getOneById($referMid);
                $content .= '由【'.$referMember['nickname'].'】，ID：【'.$referMember['id'].'】推荐了您！';
            }

            if($memberInfo) {
                $memberData['is_default'] = 1;
                $this->_start();
                try{
                    $this->_update(['id' => $memberInfo['mid']], $memberData);
                    $upWhere['id'] = ['<>', $memberInfo['mid']];
                    $upWhere['wx_openid'] = $memberInfo['wx_openid'];
                    $this->_update($upWhere, ['is_default' => 0]);
                    $this->_redisGetOneByWxOpenId($wxOpenId,$sid);
                    $this->_commit();
                }catch(\Exception $e){
                    $this->_rollBack();
                    return 'Sorry,出错啦';
                }
            }
        } else {
            $content = '您绑定店铺失败，请重新扫码！';
        }

        return $content;
    }

    public function changeDefaultShopByMid($mid)
    {
        $memberInfo = $this->_getOneById($mid);
        if(!$memberInfo) {
            return false;
        }
        $this->_start();
        try{
            $this->_update(['id' => $mid], ['is_default' => 1]);
            $upWhere['id'] = ['<>', $mid];
            $upWhere['wx_openid'] = $memberInfo['wx_openid'];
            $this->_update($upWhere, ['is_default' => 0]);
            $this->_redisGetOneByWxOpenId($memberInfo['wx_openid'],$memberInfo['shop_id']);
            $this->_commit();
        }catch(\Exception $e) {
            $this->_rollBack();
            return false;
        }
    }

    public function getMemberReferList($referType)
    {
        $keyword = request('keyword');
        $type = request('type', 0);
        $memberFields = 'id,admin_id,shop_id,nickname,avatarurl,refer_type,refer_id';
        $commissionFields = 'total_buy,total_gift,total_amount,total_member,total_money,freeze_money,already_money,able_money,mid';
        $addressFields = 'name,type,mobile,address,company_name,mid';
        $pageSize = 15;
        $pageLength = 10;
        $where = [];
        $relations = ['memberCommission'];
        $relations_columns = ['memberCommission' => $commissionFields];
        $relations_wheres = [];
        $order = ['id'=>'asc'];
        $flag = 0;
        if ($keyword && $type) {
            if (!in_array($type, [1,2])) {
                $flag = 1;
                $relations[] = 'member';
                $relations_columns['member'] = $memberFields;
                $relations_wheres = ['member' => ['refer_type' => $referType]];
                switch ($type) {
                    case 3:
                        $where = ['name' => ['like', "%{$keyword}%"]];
                        break;
                    case 4:
                        $where = ['mobile' => ['like', "%{$keyword}%"]];
                        break;
                }
            } else {
                if($type == 1) {
                    $where['id'] = $keyword;
                } else {
                    $where['nickname'] = ['like', "%$keyword%"];
                }
            }
        }
        if (!is_administrator()) {
            if (plat_identify() == 'admin') {
                $where['admin_id'] = plat_admin_id();
            } else {
                $where['shop_id'] = session('account.shop_id');
            }
        }
        if(request('shop_id')) {
            $where['shop_id'] = request('shop_id');
        }
        if ($flag) {
            $address = new Address();
            $order = ['mid'=>'asc'];
            $rows = $address->_getJionMorePageList($relations, $where, $relations_wheres, $addressFields, $relations_columns, $order, $pageSize, $pageLength);
            if ($rows['data']) {
                $arr = [];
                foreach ($rows['data'] as $k=>$v) {
                    if(!$v['member']) {
                        unset($rows['data'][$k]);
                        continue;
                    } else {
                        $item = $v['member'];
                        $item['address'] = [
                            "name" => $v['name'],
                            "type" => $v['type'],
                            "mobile" => $v['mobile'],
                            "address" => $v['address'],
                            "company_name" => $v['company_name']
                        ];
                        $item['member_commission'] = $v['member_commission'] ? $v['member_commission'] : [];
                        $arr[] = $item;
                    }

                }
                $rows['data'] = $arr;
            }
        } else {
            $where['refer_type'] = $referType;
            $relations[] = 'address';
            $relations_columns['address'] = $addressFields;
            $relations_wheres = ['address' => ['is_default' => 1]];
            $rows = $this->_getJionMorePageList($relations, $where, $relations_wheres, $memberFields, $relations_columns, $order, $pageSize, $pageLength);
        }

        if($referType == 2) {
            $refer_ids = array_column($rows['data'],'refer_id');
            $referWhere['id'] = ['in',$refer_ids];
            $refers = (new ReferCode())->_getList($referWhere,'id,code');
            $rows['data'] = collect($rows['data'])->map(function($itemD) use($refers) {
                $refers->map(function($itemR) use (&$itemD) {
                    if($itemR['id'] == $itemD['refer_id']) {
                        $itemD['refer_code'] = $itemR['code'];
                    }
                });
                return $itemD;
            })->toArray();
        }

        return $rows;
    }

    public function changeMemberWorkerId($mid, $worker_id)
    {
        $info = $this->_getOneById($mid);

        $res = $this->_update(['id'=>$mid],['worker_id'=>$worker_id]);
        if($res) {
            $key = $info['wx_openid'].'_'.$info['shop_id'];
            if($info['wx_openid'] && $this->redis->exists($key)) {
                $this->redis->del($key);
            }
            return true;
        }
        return false;
    }

    public function bindWxOpenidByMid($mid, $userInfo)
    {
        $info = $this->_getOneById($mid);
        if (!$info) {
            $content = '二维码已失效！';
        } else {
            if ($info['wx_openid']) {
                $content = '您的账号已成功关联，请勿再次操作';
            } else {
                $data = [
                    'wx_openid' => $userInfo['openid'],
                    'unionid' => isset($userInfo['unionid']) ? $userInfo['unionid'] : '',
                    'nickname' => $userInfo['nickname'],
                    'avatarurl' => $userInfo['headimgurl'],
                ];
                $res = $this->_update(['id' => $mid], $data);
                if (!$res) {
                    $content = '账号关联失败，请再次扫码操作';
                } else {
                    $this->redis->del('bind_wx_' . $mid);
                    $content = '您的账号已关联成功！';
                }
            }
        }

        return $content;
    }
}
